define(function (require, exports, module) {
    var angular = require('angular');
    require("pagination");
    require("angular-ui");
    require("/public/js/plugins/select2/select2");
    require('/public/js/myservice/contract/contract-common');
    var myMath = require('/public/js/myservice/common/my-math');
    var dialog = require("dialogplus");
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var side = require('/public/js/myservice/side');
    var moment = require('moment');

    angular.module('ContractBase', ['select2', 'ngUI', 'ContractCommonService'])
        .filter('sumProductAmount', function () {
            return function (products) {
                var amount = 0;
                $.each(products, function (i, d) {
                    if (d.__type == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, d.amount);
                });
                return amount;
            };
        })
        .filter('countSMS', function () {
            return function (products) {
                var num = 0;
                $.each(products, function (i, d) {
                    if (d.__type == 'delete') {
                        return;
                    }
                    num = myMath.add(num, d.authorization_type == 0 ? d.authorization_numeric : 0);
                });
                return num;
            };
        })
        .filter('countProject', function () {
            return function (products) {
                var company_count = 0;
                var project_count = 0;
                var room_count = 0;
                $.each(products, function (i, d) {
                    if (d.__type == 'delete') {
                        return;
                    }
                    company_count = myMath.add(company_count, d.authorization_type == 3 ? d.authorization_numeric : 0);
                    project_count = myMath.add(project_count, d.authorization_type == 2 ? d.authorization_numeric : 0);
                    room_count = myMath.add(room_count, d.authorization_type == 1 ? d.authorization_numeric : 0);
                });
                return company_count + '个公司，' + project_count + '个项目，' + room_count + '个房间';
            };
        })
        .filter('filterMinNumber', function () {
            return function (data) {
                if (data.min_price) {
                    return parseInt(data.min_price);
                }
                return 1;
            }
        })
        .service('selectSupplierService',['$rootScope', function ($rootScope) {
            var service = {
                onShowSupplier: function ($dialog, $dialogScope, supplier_id) {
                    //初始化不加载数据
                    $dialogScope.suppliers = [];
                    $dialogScope.searchKey = '';
                    $dialogScope.selectSupplier=[];
                    $dialogScope.doSearch=function (){
                        var keyword = $dialogScope.searchKey;
                        if(!keyword || keyword==''){
                            util.alert('请填写查询条件!');
                            return;
                        };

                        var url = api_prefix + 'contract/search-supplier-by-key';
                        var data = {'keyword':keyword};

                        $.ajax({
                            url:url,
                            type: 'post',
                            dataType: 'json',
                            data: data,
                            success: function (result) {
                                if (result.retCode == "0") {
                                    $dialogScope.suppliers = result.data;
                                } else {
                                    $dialogScope.suppliers = [];
                                };
                                $dialogScope.$applyAsync();
                            }
                        });
                    };
                    $dialogScope.rowClick = function(item,idx){
                        var tr = $("#grid tr")[idx];
                        $($(tr).siblings()).css('background-color','white');
                        $(tr).css('background-color','#99a2ae');
                        $dialogScope.selectSupplier.supplier_name = item.company_name;
                        $dialogScope.selectSupplier.supplier_id = item.supplier_id;
                    }
                },
                onChooseSupplier:function($data,$dialog,$dialogScope){
                    $data.supplier_name = $dialogScope.selectSupplier.supplier_name;
                    $data.supplier_id = $dialogScope.selectSupplier.supplier_id;
                }
            };

            return service;
        }])
        .controller('contractBaseCtrl', ['$scope', '$timeout', '$location', '$routeParams', 'contractCommonService','selectSupplierService', function ($scope, $timeout, $location, $routeParams, contractCommonService, selectSupplierService) {
            $scope.selectSupplierService = selectSupplierService;

            //合同基本信息
            $scope.contractBaseInfo = {
                category_id: 'b011f523-fcf2-11e4-bed8-00155d02c832',
                customer_property: 0,
                contract_status: 0,
                is_cancelled: 0,
                give_work_day: 0,
                develop_work_day: 0,
                implement_work_day: 0
            };


            // 合同类型 $location.search().contractType
            $scope.contractBaseInfo.contractTypeName = $location.search().contractType;
            $scope.contractTypes = {};
            contractCommonService.getContractTypes(function (data) {
                $scope.contractTypes = data;
                $scope.$applyAsync();
            });

            $scope.contractBaseInfo.contractType = $scope.contractTypes[$scope.contractBaseInfo.contractTypeName];
            // 旧合同
            if ($scope.contractBaseInfo.contractTypeName == null) {
                $scope.contractBaseInfo.contractType = 8;
            }

            $scope.contractBaseInfo.readOnly = false;
            if ($scope.contractBaseInfo.contractType == 5 || $scope.contractBaseInfo.contractType == 6) {
                $scope.contractBaseInfo.readOnly = true;
            }

            $scope.contractBaseInfo.balance_amount = 0;

            if($('#category_id').data('select2')){
                setTimeout(function () {
                    var categoryId = {id: "b011f523-fcf2-11e4-bed8-00155d02c832", text: "云链租用服务合同"};
                    $scope.contractBaseInfo.category_id = categoryId.id;
                    $('#category_id').data('select2').updateSelection(categoryId);

                    var bigClassInfo = {id: "2ae79470-fcf3-11e4-bed8-00155d02c832", text: "服务合同"};
                    $scope.contractBaseInfo.big_category_id = bigClassInfo.id;
                    $('#big_category_id').data('select2').updateSelection(bigClassInfo);
                    getContractSmallClass(bigClassInfo);
                }, 0);
            };

            //产品列表
            $scope.projects = [];
            //先加载下拉框
            // 合同性质下拉框处理
            $scope.ddlConfigContractNature = {
                allowClear: false,
                data: [],
                placeholder: '合同性质',
                onchange2: function (selected) {
                    var default_company_name = '';
                    var default_company;
                    var propertyname = selected.text;
                    if (propertyname == '明源签约-直属') {
                        default_company_name = '明源股份';
                    } else {
                        if (propertyname == '云链签约-直属' || propertyname == '云链签约-联营') {
                            default_company_name = '明源云链';
                        }
                    }
                    //设置合同来源自动带出
                    if(propertyname == '明源签约-直属' || propertyname == '云链签约-直属'){
                        $scope.contractBaseInfo.soure_financial = '直销合同';
                        $scope.contractBaseInfo.soure_business = '直销合同';
                    }else if(propertyname == '明源签约-联营' || propertyname == '云链签约-联营'){
                        $scope.contractBaseInfo.soure_financial = '直销合同';
                        $scope.contractBaseInfo.soure_business = '分销合同';
                    }else if(propertyname == '联营签约-云链结算'){
                        $scope.contractBaseInfo.soure_financial = '分销合同';
                        $scope.contractBaseInfo.soure_business = '分销合同';
                    }else{
                        $scope.contractBaseInfo.soure_financial = '';
                        $scope.contractBaseInfo.soure_business = '';
                    }

                    //获取公司下拉信息
                    contractCommonService.actionGetContractCompanyList(selected.id, function (data) {
                        var ddlData = [];
                        var isCompanyValid = false;
                        $.each(data, function (i, d) {
                            if (default_company_name) {
                                if (d.company_name != default_company_name) {
                                    return true;
                                } else {
                                    default_company = {id: d.company_id, text: d.company_name};
                                    ddlData.push({id: d.company_id, text: d.company_name});
                                    if (d.company_id == $scope.contractBaseInfo.company_id) {
                                        isCompanyValid = true;
                                    }
                                    return false;
                                }
                            } else {
                                ddlData.push({id: d.company_id, text: d.company_name});
                                if (d.company_id == $scope.contractBaseInfo.company_id) {
                                    isCompanyValid = true;
                                }
                            }
                        });

                        $scope.ddlConfigCompany.data = ddlData;
                        if (!isCompanyValid) {
                            //切换性质时清空签署公司
                            $scope.contractBaseInfo.company_id = null;
                        }

                        $scope.$applyAsync();

                        setTimeout(function () {
                            if (default_company) {
                                $scope.contractBaseInfo.company_id = default_company.id;
                                $scope.$applyAsync();
                                $('#idCompanyId').data('select2').updateSelection(default_company);
                            }
                        }, 0);
                    });
                }
            };

            //console.log($scope.contractBaseInfo.providers);

            // 获取产品类型
            contractCommonService.getBusinessProduct($scope.contractBaseInfo.contractTypeName ,function(data) {
                $scope.contractBaseInfo.business_product = data;
                $scope.$applyAsync();
            });
            //console.log($scope.contractBaseInfo.business_product);

            //获取合同性质列表
            contractCommonService.getContractNatures(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    if($scope.contractBaseInfo.contractType == 5 && (d.property_name=="云链签约-联营" || d.property_name == '云链签约-直属')){
                        ddlData.push({id: d.property_id, text: d.property_name});
                    }
                    if(($scope.contractBaseInfo.contractType == 7)&& (d.property_name=="云链直销")){
                        ddlData.push({id: d.property_id, text: d.property_name});
                    }
                    if(($scope.contractBaseInfo.contractType == 3 || $scope.contractBaseInfo.contractType == 6) && d.property_name=="云链直销"){
                        ddlData.push({id: d.property_id, text: d.property_name});
                    }
                    if($scope.contractBaseInfo.contractType == 4 && (d.property_name=="云链直销" || d.property_name=="明源签约-直属" || d.property_name=="联营签约-云链结算")){
                        ddlData.push({id: d.property_id, text: d.property_name});
                    }
                    if($scope.contractBaseInfo.contractType == 1 || $scope.contractBaseInfo.contractType == 2){
                        ddlData.push({id: d.property_id, text: d.property_name});
                    }
                });
                $scope.ddlConfigContractNature.data = ddlData;
                $scope.$applyAsync();
            });

            // 合同签署公司下拉框处理
            $scope.ddlConfigCompany = {
                allowClear: false,
                data: [{id: 1, text: '明源云链'}],
                placeholder: '合同签署公司'
            };

            // 合同类别下拉框处理
            $scope.ddlConfigContractCategory = {
                allowClear: false,
                data: [{id: 1, text: '云链租用服务合同'}],
                placeholder: '合同类别'
            };

            //获取类别下拉信息
            contractCommonService.getContractCategories(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push({id: d.category_id, text: d.category_name});
                });
                $scope.ddlConfigContractCategory.data = ddlData;
                $scope.$applyAsync();
            });

            // 合同小类下拉框处理
            $scope.ddlConfigContractSmallClass = {
                allowClear: false,
                data: [],
                placeholder: '合同小类'
            };

            // 合同大类下拉框处理
            $scope.ddlConfigContractBigClass = {
                allowClear: false,
                data: [],
                placeholder: '合同大类',
                onchange2: function (item) {
                    if (!item || !item.id) {
                        return;
                    }
                    getContractSmallClass(item);
                }
            };
            var getContractSmallClass = function (item) {
                contractCommonService.getContractSmallClass(item.id, function (data) {
                    var ddlData = [],
                        _initLittleClassInfo;

                    $.each(data, function (i, d) {
                        if (d.littler_category_name == '云链租用') {
                            _initLittleClassInfo = {id: d.littler_category_id, text: d.littler_category_name};
                        }
                        ddlData.push({id: d.littler_category_id, text: d.littler_category_name});
                    });
                    $scope.ddlConfigContractSmallClass.data = ddlData;

                    $scope.$applyAsync();

                    setTimeout(function () {
                        if (_initLittleClassInfo) {
                            $scope.contractBaseInfo.littler_category_id = _initLittleClassInfo.id;
                            $scope.contractBaseInfo.littler_category_name = _initLittleClassInfo.text;
                            $('#idSmallClass').data('select2').updateSelection(_initLittleClassInfo);
                        }
                    }, 0);
                })
            };

            //获取大类下拉信息
            contractCommonService.getContractBigClass(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push({id: d.big_category_id, text: d.big_category_name});
                });
                $scope.ddlConfigContractBigClass.data = ddlData;
                $scope.$applyAsync();
            });

            //合同签约地区下拉框处理
            $scope.ddlConfigContractSignArea = {
                allowClear: false,
                data: [{id: 1, text: '北京'}],
                placeholder: '合同签约地区'
            };
            //获取签约地区下拉信息
            contractCommonService.getContractAreas(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push({id: d.regionId, text: d.regionName});
                });
                $scope.ddlConfigContractSignArea.data = ddlData;
                $scope.$applyAsync();
            });

            //产品下拉框数据
            $scope.ddlConfigProjectsData = [];

            //获取产品下拉信息
            contractCommonService.getProducts(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push($.extend({}, {id: d.application_id, text: d.application_name}, d));
                });
                $scope.ddlConfigProjectsData = ddlData;
            });

            //获取合同信息
            $scope.loadContract = function (contractId) {
                if (contractId) {
                    //$scope.contractBaseInfo.contractTypeName =
                    contractCommonService.getContract(contractId, function (data) {
                        setTimeout(function () {
                            $scope.contractBaseInfo = data.contract;
                            $scope.projects = data.application;
                            $scope.products = data.products;
                            $scope.linkcontract = data.linkcontract;
                            $scope.linkcontractother = data.linkcontractother;
                            $scope.linkcontractrelation = data.linkcontractrelation;

                            if (data.contract) {
                                $scope.contractBaseInfo.contract_code_readonly = data.contract.contract_code;
                            }
                            $('#idCustomerName').length && $('#idCustomerName').data('select2').updateSelection({text: data.contract.customer_name || ''});
                            if(data.contract.sign_people_name){
                                $('#idSigner').length && $('#idSigner').data('select2').updateSelection({text: data.contract.sign_people_name || data.contract.sign_people_id});
                            }
                            if(data.contract.area_name){
                                $('#idAreaid').length && $('#idAreaid').data('select2').updateSelection({text: data.contract.area_name || data.contract.area_id});
                            }
                            if(data.linkcontractother && data.linkcontractother.sign_people_name){
                                $('#idSigner2').length && $('#idSigner2').data('select2').updateSelection({text: data.linkcontractother.sign_people_name || data.linkcontract.sign_people_id});
                            }
                            $('#idCompanyId').length && $('#idCompanyId').data('select2').updateSelection({text: data.contract.company_name || ''});
                            var signDate = moment(data.contract.sign_date, 'YYYY-MM-DD HH:mm:ss');
                            if (signDate.isValid()) {
                                $scope.contractBaseInfo.sign_date = signDate.format('YYYY-MM-DD');
                            }
                            var inputDate = moment(data.contract.input_date, 'YYYY-MM-DD HH:mm:ss');
                            if (inputDate.isValid()) {
                                $scope.contractBaseInfo.input_date = inputDate.format('YYYY-MM-DD');
                            }
                            var effect_date = moment(data.contract.effect_date, 'YYYY-MM-DD HH:mm:ss');
                            if (effect_date.isValid()) {
                                $scope.contractBaseInfo.effect_date = effect_date.format('YYYY-MM-DD');
                            }

                            // 合同业务类型
                            $scope.contractBaseInfo.contractTypeName = data.contract.business_type;
                            $scope.contractBaseInfo.contractType = $scope.contractTypes[$scope.contractBaseInfo.contractTypeName];

                            $scope.$applyAsync();
                        }, 500);

                    });
                }
            };

            var contractId = $routeParams.id;
            var fromContractId = $routeParams.pid;
            if (contractId) {
                //编辑模式先设为只读（复核状态），避免复核的合同先显示编辑按钮再隐藏导致的刷新
                $scope.contractBaseInfo.contract_status = 1;
                $scope.loadContract(contractId);
            } else if (fromContractId) {
                contractCommonService.getContract(fromContractId, function (data) {
                    setTimeout(function () {
                        $scope.contractBaseInfo = angular.extend(data.contract, {
                            contract_id: null,
                            contract_code: null,
                            input_date: null,
                            balance_status: 0,
                            is_violated: 0,
                            contract_status: 0,
                            is_cancelled: 0
                        });
                        if (data.application) {
                            $.each(data.application, function (i, d) {
                                d['__type'] = 'add';
                            })
                        }
                        $scope.projects = data.application;

                        $('#idCustomerName').length && $('#idCustomerName').data('select2').updateSelection({text: data.contract.customer_name || ''});
                        if(data.contract.sign_people_name) {
                            $('#idSigner').length && $('#idSigner').data('select2').updateSelection({text: data.contract.sign_people_name || data.contract.sign_people_id});
                        }
                        if(data.linkcontractother && data.linkcontractother.sign_people_name){
                            $('#idSigner2').length && $('#idSigner2').data('select2').updateSelection({text: data.linkcontractother.sign_people_name || data.linkcontract.sign_people_id});
                        }
                        $('#idCompanyId').length && $('#idCompanyId').data('select2').updateSelection({text: data.contract.company_name || ''});

                        var signDate = moment(data.contract.sign_date, 'YYYY-MM-DD HH:mm:ss');
                        if (signDate.isValid()) {
                            $scope.contractBaseInfo.sign_date = signDate.format('YYYY-MM-DD');
                        }
                        var inputDate = moment(data.contract.input_date, 'YYYY-MM-DD HH:mm:ss');
                        if (inputDate.isValid()) {
                            $scope.contractBaseInfo.input_date = inputDate.format('YYYY-MM-DD');
                        }
                        $scope.contractBaseInfo.sign_amount = 0;
                        $scope.contractBaseInfo.rent_amount = 0;
                        $scope.contractBaseInfo.delivery_amount = 0;
                        $scope.contractBaseInfo.supplier_name = '';
                        $scope.$applyAsync();
                    }, 500);

                });
            }

            // 客户下拉框处理
            $scope.ddlConfigCustomer = {
                allowClear: false,
                placeholder: '客户简称',
                ajax: {
                    url: api_prefix + "erp-interface/get-erp-customer-info",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                            $.each(data, function (i, d) {
                                d.text = d.CstName;
                                d.id = d.CSTGUID;
                            });
                        }
                        return {results: data};
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal) {
                    $scope.contractBaseInfo.top_customer_name = newVal.DjCstName;
                    $scope.contractBaseInfo.customer_full_name = newVal.CstFullName;
                    $scope.contractBaseInfo.customer_name = newVal.CstName;
                    $scope.contractBaseInfo.customer_code = newVal.CstShortCode;
                },
                formatResult: formatCustomer,
                formatSelection: formatCustomerSelection // omitted for brevity, see the source of this page
            };
            function formatCustomer(repo) {
                if (repo.loading) return repo.text;

                return repo.text;
            }

            function formatCustomerSelection(repo) {
                return repo.text;
            }

            // 合同签约人下拉框处理
            $scope.ddlConfigContractSigner = {
                allowClear: false,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal) {
                    $scope.contractBaseInfo.area_name = newVal.BUName;
                    $scope.contractBaseInfo.area_id = newVal.BUGUID;
                    $scope.contractBaseInfo.area_code = newVal.BUCode;

                    $scope.contractBaseInfo.sign_people_department_id = newVal.DepartmentId;
                    $scope.contractBaseInfo.sign_people_department_name = newVal.DepartmentName;
                },
                formatResult: formatRepo,
                formatSelection: formatRepoSelection // omitted for brevity, see the source of this page
            };

            // 合同所属区域下拉框处理
            $scope.ddlConfigContractAreaid = {
                allowClear: false,
                ajax: {
                    url: api_prefix + "contract/get-area-info",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                            $.each(data, function (i, d) {
                                d.text = d.BUName;
                                d.id = d.BUGUID;
                            });
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                }
            };

            function formatRepo(repo) {
                if (repo.loading) return repo.text;

                var markup = '<div class="clearfix" style="width: 300px;">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-6">' + repo.UserName + '</div>' +
                    '<div class="col-sm-18">' + repo.BUName + '</div>' +
                    '</div></div>';

                return markup;
            }

            function formatRepoSelection(repo) {
                return repo.text;
            }

            $scope.ddl2Customer = '';
            $scope.ddl2Type = '';
            $scope.ddl2Company = '';
            $scope.ddl2Category = '';
            $scope.ddl2BigClass = '';
            $scope.ddl2SmallClass = '';
            $scope.ddl2Signer = '';
            $scope.ddl2Areaid = '';
            $scope.ddl2SignArea = '';
            $scope.ddl2Nature = '';

            function formatProduct(repo) {
                if (repo.loading) return repo.text;

                var markup = '<div class="clearfix">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-24">' + repo.application_name + '</div>' +
                    '</div></div>';

                return markup;
            }

            function formatProductSelection(repo) {
                return repo.application_name;
            }

            //新增/修改产品
            $scope.onProductEditShow = function ($data, $dialog, $dialogScope, oldProd) {
                $dialogScope.oldProd = oldProd;
                $dialogScope.contypes = ['', '新增', '续签'];
                if($data) {
                    if($data.contract_type == 1) {
                        $dialogScope.contype = '新增';
                    } else if ($data.contract_type == 2) {
                        $dialogScope.contype = '续签';
                    } else {
                        $dialogScope.contype = '';
                    }
                } else {
                    $dialogScope.contype = '';
                }

                var isinit = true;

                $dialogScope.$watch('data.authorization_numeric', function (itemVal) {
                    if (!$dialogScope.oldProd || !isinit) {
                        $dialogScope.data.amount = myMath.mul(itemVal, $dialogScope.data.price);
                    }
                });

                $dialogScope.ddlConfigProjects = {
                    allowClear: false,
                    data: $scope.ddlConfigProjectsData,
                    placeholder: '产品名称',
                    onchange2: function (item) {
                        $dialogScope.data.authorization_type = item.authorization_type;
                        $dialogScope.data.application_name = item.application_name;
                        $dialogScope.data.application_id = item.application_id;

                        if (!$dialogScope.oldProd || !isinit) {
                            $dialogScope.data.unit = item.LicensingStandards;
                            $dialogScope.data.price = item.BenchmarkPrice;
                            $dialogScope.data.amount = 0;
                            $dialogScope.data.authorization_numeric = 0;
                        }
                        isinit = false;
                        $dialogScope.$applyAsync();
                    }
                };

            };
            $scope.addContractProduct = function ($data, $dialog, $dialogScope) {
                $dialogScope.data.contract_type = $dialogScope.contype == '新增' ? 1 : ($dialogScope.contype == '续签' ? 2 : '');
                $scope.projects.push($.extend({__type: 'add'}, $data));
            };
            $scope.saveContractProduct = function ($data, $dialog, $dialogScope) {
                $dialogScope.data.contract_type = $dialogScope.contype == '新增' ? 1 : ($dialogScope.contype == '续签' ? 2 : '');
                angular.extend($dialogScope.oldProd, $.extend({__type: 'update'}, $data));
            };

            $scope.delProject = function (proj) {
                /**
                 * 删除产品
                 */
                util.confirm('确定要删除此产品吗？', {
                    ok: function () {
                        angular.extend(proj, {__type: 'delete'});
                        $scope.$applyAsync();
                    }
                });
            };

            if (Math.floor($scope.contractBaseInfo.rent_amount) == Math.floor($scope.contractBaseInfo.delivery_amount) == 0) {
                $scope.contractBaseInfo.sign_amount = 0;
                $scope.contractBaseInfo.rent_amount = 0;
                $scope.contractBaseInfo.delivery_amount = 0;
            }

            $scope.$watch('contractBaseInfo.sign_amount', function (newData) {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.rent_amount, $scope.contractBaseInfo.delivery_amount)) {
                    $scope.contractBaseInfo.delivery_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.rent_amount);
                }
            });
            $scope.$watch('contractBaseInfo.rent_amount', function (newData) {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.delivery_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.rent_amount);
                }
            });
            $scope.$watch('contractBaseInfo.delivery_amount', function (newData) {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.rent_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.delivery_amount);
                }
            });

            $scope.save = function () {
                /**
                 * 保存
                 */
                var isNew = contractId ? false : true;
                //收集合同信息
                var baseInfo = $scope.contractBaseInfo;
                var projectsInfo = $scope.projects;

                if (baseInfo.supplier_name != '') {
                    baseInfo.supplier_id = getSupplierIdByName(baseInfo.supplier_name) || '';
                }

                var businessType = baseInfo.business_type || baseInfo.contractTypeName;
                if (businessType.length > 0) {
                    baseInfo.business_type_id = getBusinessTypeIdByName(businessType);
                }

                //delete baseInfo['contractTypeName'];
                //delete baseInfo['contractType'];
                //delete baseInfo['readOnly'];

                var post_data = {
                    contract: baseInfo,
                    product: projectsInfo
                };
                var url;
                if (isNew) {
                    url = api_prefix + "/contract/add-contract";
                } else {
                    url = api_prefix + "/contract/update-contract";
                }

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success: function (json) {
                        if (json.retCode === "0") {
                            if (isNew) {
                                //$location.path("base").search({id: json.data});
                                $location.search({id: json.data,'contractType':$scope.contractBaseInfo.contractTypeName});
                                contractId = json.data;
                                setTimeout(function () {
                                    side.refresh();
                                }, 1000);
                                util.alert('合同创建成功', {
                                    ok: function () {
                                        setTimeout(function () {
                                            side.refresh();
                                        }, 500);
                                    }
                                });
                            } else {
                                util.alert("保存成功");
                            }

                            $scope.loadContract(contractId);

                        } else {
                            util.alert("保存失败：" + json.errMsg);
                        }
                    }
                });
            };

            var getSupplierIdByName = function(supplier_name) {
                var supplier_id = '';
                contractCommonService.getSupplierInfoByName(supplier_name, function (data) {
                    supplier_id = data.supplier_id;
                });

                return supplier_id;
            };

            var getBusinessTypeIdByName = function(business_type) {
                var business_type_id = '';
                contractCommonService.getBusinessTypeIdByName(business_type, function(data) {
                    console.log(data.business_type_id);
                    business_type_id = data.business_type_id;
                });

                return business_type_id;
            };

            $scope.verify = function () {
                /**
                 * 提交复核
                 */

            }
        }]);
});